﻿<title>新增订单</title>
<link href="../../layuiadmin/layui/css/layui.css" rel="stylesheet" />

<div class="layui-fluid">
    <style>
        .layui-table-cell {
            overflow: visible;
        }

        .layui-table-box {
            overflow: visible;
        }

        .layui-table-body {
            overflow: visible;
        }
        /* 设置下拉框的高度与表格单元相同 */
        td .layui-form-select {
            margin-top: -10px;
            margin-left: -15px;
            margin-right: -15px;
        }
    </style>
    <script type="text/html" id="selecta">
        <select name="selectDemo" lay-filter="selectDemo" lay-search></select>
    </script>
    <div class="layui-card">
        <div class="layui-card-body" style="padding: 15px;">
            <form class="layui-form" id="fromId" action="#">
                <script type="text/html" id="toolbarDemo">
                    <div align="right" class="layui-btn-container">
                        <button id="addTable" class="layui-btn layui-btn-sm layui-btn-normal" lay-event="add">添加行</button>
                    </div>
                </script>
                <script type="text/html" id="bar">
                    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
                </script>
                <table id="demo" lay-filter="tableFilter"></table>
                <div class="layui-form-item" style="margin-top: 30px;text-align: center;">
                    <button class="layui-btn" lay-submit="" lay-filter="*">保存</button>
                </div>
                <!--送货方式-->
            </form>
        </div>
    </div>
</div>
<script src="../../layuiadmin/layui/layui.js"></script>
<script src="../../layuiadmin/js/cookie.js"></script>
<script>
    var clickCount = 0;
    layui.config({
        base: '../../../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['jquery', 'table', 'layer', 'laydate', 'form'], function () {
        var $ = layui.jquery,
            table = layui.table,
            form = layui.form,
            layer = layui.layer,
            element = layui.element,
            laydate = layui.laydate,
            router = layui.router();
        //验证用户是否登录
        if ($.cookie("loginid") == "" || $.cookie("loginid") == null || $.cookie("loginid") == "null" || $.cookie("loginid") == undefined || $.cookie("loginid") == "undefined") {
            $.removeCookie("id", { path: "/", sucue: true });//用户id
            $.removeCookie("loginid", { path: "/", sucue: true });//登录账号
            $.removeCookie("username", { path: "/", sucue: true });//用户名
            $.removeCookie("role", { path: "/", sucue: true });//权限
            $.removeCookie("islookme", { path: "/", sucue: true });//权限
            window.location.href = "../login/login.html";
        }
        
        //时间控件
        laydate.render({
            elem: '#date' //指定元素
        });
        var tabledata;
        //第一个实例 加载表格
        var tableIns = table.render({
            elem: '#demo'
            , id: 'product_table'
            , toolbar: '#toolbarDemo'
            , defaultToolbar: []
            , limit: 100
            , cols: [[ //表头
                { field: 'product_value', title: '款号', edit: 'text', event: 'select_product' }
                , { field: 'id', hide: true }
                , { field: 'color', title: '颜色', edit: 'text' }
                , { field: 'colorname', title: '颜色名称', edit: 'text' }
                , { field: 'size_wm', title: '外码', edit: 'text' }
                , { field: 'size_nm', title: '内码', edit: 'text' }
                , { field: 'product_name', title: '品名', edit: 'text' }
                , { field: 'jg', title: '价格', edit: 'text' }
                , { field: 'nf', title: '年份', edit: 'text' }
                , { field: 'jj', title: '季节', edit: 'text' }
                , { field: 'sl', title: '数量', edit: 'text' }
                , { field: 'remark', title: '备注', edit: 'text' }
                , { title: '操作', align: 'center', toolbar: '#bar', event: 'del' }
            ]]
            , data: [{
                "product_value": ""
                ,"id":""
                , "color": ""
                , "colorname": ""
                , "size_wm": ""
                , "size_nm": ""
                , "product_name": ""
                , "jg": ""
                , "nf": ""
                , "jj": ""
                , "sl": ""
                , "remark": ""
            }]
            , done: function (res, curr, count) {
                //如果是异步请求数据方式，res即为你接口返回的信息。
                //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                tabledata = res.data;
                //去掉下拉框的失焦事件 否则在下拉框里输入值 失焦后变回下拉选项里的值了 没有需要的同学忽略掉即可
                $(".layui-table-body, .layui-table-box, .layui-table-cell").css('overflow', 'visible');
            }
        });
        //头工具栏添加按钮事件
        table.on('toolbar(tableFilter)', function (obj) {
            if (obj.event === 'add') {
                tabledata.push({
                    "product_value": ""
                    , "id": ""
                    , "color": ""
                    , "colorname": ""
                    , "size_wm": ""
                    , "size_nm": ""
                    , "product_name": ""
                    , "jg": ""
                    , "nf": ""
                    , "jj": ""
                    , "sl": ""
                    , "remark": ""
                })
                table.reload('product_table', {
                    data: tabledata
                });
            };
        });
        //框内事件
        table.on('tool(tableFilter)', function (obj) {
            var data = obj.data,
                event = obj.event,
                tr = obj.tr; //获得当前行 tr 的DOM对象;
            switch (event) {
                case "dateti":
                    console.log("a");
                    var newdata = {};
                    var field = $(this).data('field');
                    laydate.render({
                        elem: this.firstChild
                        , show: true //直接显示
                        , closeStop: this
                        , type: 'datetime'
                        , format: "yyyy-MM-dd"
                        , done: function (value, date) {
                            newdata[field] = value;
                            obj.update(newdata);
                        }
                    });
                    break;
                case "del":
                    var oldData = table.cache["product_table"];
                    oldData.splice(obj.tr.data('index'), 1);
                    layer.msg("删除成功", { time: 10 }, function () {
                        table.reload('product_table', { data: oldData });
                    })
                    break;
                case "select_product":
                    var rowIndex = $(obj.tr).attr("data-index");
                    var field = $(this).data('field');
                    var index = layer.open({
                        type: 2,
                        area: ['90%', '95%'],
                        shade: false,
                        maxmin: true,
                        title: '选择条码',
                        btn: ["确定", '关闭'],
                        content: 'select_tm.html',
                        yes: function (index, layero) {
                            var objdata = $(layero).find("iframe")[0].contentWindow;
                            $(layero).find("iframe")[0].contentWindow.$('#saveBtn').click();//执行子页面的按钮点击事件
                            var mJson = objdata.$('#uidsub').val();//获取子页面绑定的值
                            if (mJson != "") {
                                var _mJson = $.parseJSON(mJson);//转成Json对象
                                $(".layui-table-box tbody tr[data-index='" + rowIndex + "'] td[data-field='product_value']").text(_mJson[0].product_value);
                                $(".layui-table-box tbody tr[data-index='" + rowIndex + "'] td[data-field='id']").text(_mJson[0].id);
                                $(".layui-table-box tbody tr[data-index='" + rowIndex + "'] td[data-field='color']").text(_mJson[0].yscode);
                                $(".layui-table-box tbody tr[data-index='" + rowIndex + "'] td[data-field='colorname']").text(_mJson[0].ysname);
                                $(".layui-table-box tbody tr[data-index='" + rowIndex + "'] td[data-field='size_wm']").text(_mJson[0].size_wm);
                                $(".layui-table-box tbody tr[data-index='" + rowIndex + "'] td[data-field='size_nm']").text(_mJson[0].size_nm);
                                $(".layui-table-box tbody tr[data-index='" + rowIndex + "'] td[data-field='product_name']").text(_mJson[0].product_name);
                                $(".layui-table-box tbody tr[data-index='" + rowIndex + "'] td[data-field='jg']").text(_mJson[0].price);
                                $(".layui-table-box tbody tr[data-index='" + rowIndex + "'] td[data-field='nf']").text(_mJson[0].nf);
                                $(".layui-table-box tbody tr[data-index='" + rowIndex + "'] td[data-field='jj']").text(_mJson[0].jj);
                                //同步更新缓存对应的值（真正的更新）
                                obj.update({
                                    product_value: _mJson[0].product_value
                                    , id: _mJson[0].id
                                    , color: _mJson[0].yscode
                                    , colorname: _mJson[0].ysname
                                    , size_wm: _mJson[0].size_wm
                                    , size_nm: _mJson[0].size_nm
                                    , product_name: _mJson[0].product_name
                                    , jg: _mJson[0].price
                                    , nf: _mJson[0].nf
                                    , jj: _mJson[0].jj
                                });
                                table.reload('product_table', {
                                    data: tabledata
                                });
                            }
                        },
                        cancel: function (index, layero) {
                            // 取消的操作
                        },
                        end: function () { }
                    });
                    break;
            }
        })

        //事件
        var active = {
           add: function () {
                var index = layer.open({
                    type: 2
                    , title: '购物车'
                    , content: 'cartlist.html'
                    , maxmin: true
                    , area: [($(window).width() * 0.5) + 'px', ($(window).height() * 0.5) + 'px']
                    , cancel: function (index, layero) {
                        //取消的操作
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = window[layero.find('iframe')[0]['name']];//得到iframe页的窗口对象，执行iframe页的方法：
                        var content = layero.find("iframe")[0].contentWindow.$("#lbl_ysdh").text();
                        if (content == "" || content == null || content == undefined) {
                        }
                        else {
                            //iframeWin.submit('save');//调用子页面的方法，得到子页面返回的ids
                            layer.close(index);//需要手动关闭窗口
                        }
                    },
                    end: function () {
                        table.reload('testReload', {//刷新列表
                            where: { //请求参数
                                lddocno: $('#lddocno').val()
                                , dcname: $('#dcname').val()
                                , gkname: $('#gkname').val()
                                , status: $("select[name='status']").val()
                            }
                        });
                    }
                });
                layer.full(index);
            }
        };

        var yz_zzs = /^[1-9]*[1-9][0-9]*$/;
        //提交数据到后台保存
        form.on('submit(*)', function (data) {
            debugger
            //明细
            var t = tabledata.length;
            if (t > 0) {
                for (var j = 0; j < tabledata.length; j++) {
                    var indexs = tabledata[j].LAY_TABLE_INDEX;
                    if (indexs === "" || indexs === null || indexs === undefined) {
                        layer.msg('最少要填写一行', { icon: 5 });
                        return false;
                    }
                    var sl = tabledata[j].sl;
                    if (sl === "" || sl === null || sl === undefined) {
                        layer.msg('必须要填写数量', { icon: 5 });
                        return false;
                    }
                    else if (!yz_zzs.test(sl)) {
                        layer.msg('必须是大于0的正整数！', { icon: 5 });
                        return false;
                    }
                }
            }
            else {
                layer.msg('最少要新增一行', { icon: 5 });
                return false;
            }
            //主体信息
            var arrayObj_main = new Array();
            var main = {
                "id": $.cookie("id"),
                "loginid": $.cookie("loginid"),
                "username": $.cookie("username")
            };
            arrayObj_main.push(main);
            debugger
            //  要将tabledata json这样传到后台就可以json序列化循环数据库事物插入
            //防止多次点击
            if (clickCount >= 2) {
                return false;
            }
            else {
                $.ajax({
                    type: "post",
                    async: true,
                    url: 'ashx/list.ashx?type=order_save',
                    data: JSON.stringify({ 'ArrayObj_main': arrayObj_main, 'ArrayObj_mx': tabledata }),
                    dataType: "json",
                    success: function (res) {
                        var index = parent.layer.getFrameIndex(window.name);
                        if (res.flag == "True") {
                                clickCount++;
                                layer.msg(res.remsg, {
                                    time: 2000,
                                    end: function () {
                                        parent.layer.close(index);
                                        window.parent.location.reload();
                                    }
                                })
                           
                        }
                        else {
                            layer.alert(res.remsg);
                        }
                    }
                })
            }
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });



    })
</script>

